package com.gzu.emr.controller;

import com.gzu.emr.common.ServiceResultEnum;
import com.gzu.emr.controller.param.PrescriptionAddPraram;
import com.gzu.emr.dto.Prescription;
import com.gzu.emr.service.PrescriptionService;
import com.gzu.emr.service.impl.PrescriptionServiceImpl;
import com.gzu.emr.util.BeanUtil;
import com.gzu.emr.util.Result;
import com.gzu.emr.util.ResultGenerator;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.gzu.emr.util.ResultGenerator.genFailResult;
import static com.gzu.emr.util.ResultGenerator.genSuccessResult;

/**
 * 处方控制器
 *
 * @author chuchu
 * @version 1.0
 * @date 2023-07-20
 **/
@RestController
@Slf4j
@RequestMapping("/prescription")
public class PrescriptionController {

    @Resource
    PrescriptionService prescriptionService;

    @PostMapping("/save")
    @ResponseBody
    public Result save(@RequestBody @Valid PrescriptionAddPraram params) {

        Prescription prescription = new Prescription();
        prescription.setCreateTime(new Date());
        prescription.setAmount(params.getAmount());
        BeanUtil.copyProperties(params, prescription);
        Integer row = prescriptionService.savePrescription(prescription);
        var result = ServiceResultEnum.SUCCESS.getResult();
        if (row == 1) {
            return genSuccessResult();
        } else {
            return genFailResult(result);
        }
    }

    @PostMapping("/save/drugs")
    @ResponseBody
    public Result saveDrugs(@RequestBody Map<String, Object> params) {
        var preId = params.get("pre_id");
        if(preId == null) {
            return genFailResult("bad request body");
        }
        var drugIdList = params.get("drug_ids");
        if(drugIdList == null) {
            return genFailResult("bad request body");
        }
        var countList = params.get("counts");
        if(countList == null) {
            return genFailResult("bad request body");
        }

        List<Integer> listId = (List<Integer>) drugIdList;
        List<Integer> listCount = (List<Integer>) countList;
        if(listId.size() != listCount.size()) {
            return genFailResult("bad request body");
        }

        prescriptionService.savePrescriptionAndDrugs((Integer) preId, listId, listCount);

        return genSuccessResult();
    }



}
